package com.shop.shop_end.controller;

import cn.hutool.core.io.FileUtil;
import com.shop.shop_end.config.AuthAccess;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.Servlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

//文件处理
@RestController
@RequestMapping("file")
public class FileController {
//    @Resource
//    private ImagesService imagesService;
    @Value("${ip:localhost}")
    private String ip;
    @Value("${server.port}")
    private String port;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    //上传
    @PostMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //文件的原始名称
        String mainName = FileUtil.mainName(originalFilename);//文件的名称（不包含.后缀）
        String extName = FileUtil.extName(originalFilename); //文件的后缀名，不包含.
        if (!FileUtil.exist(ROOT_PATH)){//判断文件是否存在
            FileUtil.mkdir(ROOT_PATH);//不存在就新建一个
        }
        //判断上传的文件名是不是已经存在了，存在的话就重新命名
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)){
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." +extName;
        }
        //得到最终的保存的文件地址拼接文件名
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);//存储文件到本地
        //返回文件的地址
        String url = "http://" + ip + ":" + port + "/file/download/" + originalFilename;
        return ResultUtil.ok(url);
    }


    //下载，也可以当做是预览解析
    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); //附件下载，没加这行就是默认下载
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8")); //预览
        String filePath = ROOT_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath)){//文件不存在直接return，不处理
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);//字节流去读取处理这个文件
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes); //数组是一个字节数组，也就是文件的字节流数组
        outputStream.flush();//刷新
        outputStream.close();//关闭字节流
    }
}
